package com.heima.comment.service.impl;

import com.heima.comment.service.CommentRepayService;
import com.heima.common.exception.CustException;
import com.heima.feigns.UserFeign;
import com.heima.model.comment.dtos.CommentRepayDTO;
import com.heima.model.comment.dtos.CommentRepayLikeDTO;
import com.heima.model.comment.dtos.CommentRepaySaveDTO;
import com.heima.model.comment.pojos.ApComment;
import com.heima.model.comment.pojos.ApCommentLike;
import com.heima.model.comment.pojos.ApCommentRepay;
import com.heima.model.comment.pojos.ApCommentRepayLike;
import com.heima.model.comment.vo.ApCommentRepayVO;
import com.heima.model.comment.vo.ApCommentVo;
import com.heima.model.common.dtos.ResponseResult;
import com.heima.model.common.enums.AppHttpCodeEnum;
import com.heima.model.user.pojos.ApUser;
import com.heima.model.user.thread.AppThreadLocalUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Sort;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

@Slf4j
@Service
public class CommentRepayServiceImpl implements CommentRepayService {
    @Autowired
    MongoTemplate mongoTemplate;
    @Autowired
    UserFeign userFeign;

    @Override
    public ResponseResult loadCommentRepay(CommentRepayDTO dto) {
        //        1. 参数校验 校验文章id 校验size
        dto.check();
//        2. 根据条件查询评论列表
//                (评论id  , 创建时间 小于最小时间 , 截取size条记录 , 创建时间降序)
        String commentId = dto.getCommentId();
        Date minDate = dto.getMinDate();
        Integer size = dto.getSize();
        Query query = Query.query(Criteria.where("commentId").is(commentId).and("createdTime").lt(minDate))
                .with(Sort.by(Sort.Direction.DESC,"createdTime"))
                .limit(size);
        List<ApCommentRepay> apCommentRepays = mongoTemplate.find(query, ApCommentRepay.class);
//        3. 判断当前用户是否登录
        ApUser user = AppThreadLocalUtils.getUser();
        if (user==null){
//        4. 如果未登录直接返回评论列表
            return ResponseResult.okResult(apCommentRepays);
        }
//        5. 如果登录了 需要检查在当前评论列表中 哪些评论登陆人点赞过
//                (将所有ApComment 转成 ApCommentVO , 点过赞的operation设置为0)
//                 commentId  in    评论id列表   authorId = 登录人id
//        获取评论ID列表
        List<String> IDs = apCommentRepays.stream().map(ApCommentRepay::getId).collect(Collectors.toList());
//        获取所有点赞列表
        List<ApCommentRepayLike> likeList = mongoTemplate.find(Query.query(Criteria.where("commentRepayId").in(IDs)), ApCommentRepayLike.class);
        List<ApCommentRepayVO> repayVOList = apCommentRepays.stream()
                .map(o -> {
//                    将ApComment映射为ApCommentVO
                    ApCommentRepayVO repayVO = new ApCommentRepayVO();
                    BeanUtils.copyProperties(o, repayVO);
//                    如果当前评论id在点赞记录中存在  设置operation字段为0  不存在不用做任何处理
                    for (ApCommentRepayLike like : likeList) {
                        if (like.getCommentRepayId().equals(o.getId())){
                            repayVO.setOperation((short)0);
                        }
                    }
                    return repayVO;
                })
                .collect(Collectors.toList());

        return ResponseResult.okResult(repayVOList);
    }

    @Override
    public ResponseResult saveCommentRepay(CommentRepaySaveDTO dto) {
        //        1. 校验参数  校验是否登录
        ApUser user = AppThreadLocalUtils.getUser();
        if (user == null){
            log.error("saveCommentRepay 用户未登录");
            CustException.cust(AppHttpCodeEnum.NEED_LOGIN);
        }
//        2. 阿里云校验评论内容是否违规
//       (简单:  此步不做      普通: 阿里云检测有问题提示      高级:  有问题不报异常，替换为**)

//        3. 远程查询当前登陆用户信息
        ResponseResult<ApUser> responseResult = userFeign.findUserById(user.getId());
        if (responseResult.getCode()!=0) {
            log.error("saveCommentRepay 调用userFeign失败，code!=0,userID为{}",user.getId());
            CustException.cust(AppHttpCodeEnum.SERVER_ERROR);
        }
        ApUser apUser = responseResult.getData();
//        4. 创建评论信息，并保存到mongo
        try {
            handleSave(apUser,dto);
        } catch (Exception e) {
            e.printStackTrace();
            log.error("saveComment 保存评论出错");
            CustException.cust(AppHttpCodeEnum.SERVER_ERROR);
        }
        return ResponseResult.okResult();
    }

    private void handleSave(ApUser apUser, CommentRepaySaveDTO dto) {
        ApCommentRepay commentRepay = new ApCommentRepay();
        commentRepay.setAuthorId(apUser.getId());
        commentRepay.setAuthorName(apUser.getName());
        commentRepay.setCommentId(dto.getCommentId());
        commentRepay.setContent(dto.getContent());
        commentRepay.setLikes(0);
        commentRepay.setCreatedTime(new Date());

//        保存评论回复
        mongoTemplate.save(commentRepay);
        ApComment apComment = mongoTemplate.findOne(Query.query(Criteria.where("id").is(dto.getCommentId())), ApComment.class);
        if (apComment == null){
            log.error("saveCommentRepay 查询 apComment 失败，CommentId为{}",dto.getCommentId());
            CustException.cust(AppHttpCodeEnum.PARAM_INVALID);
        }
//        更新评论信息 回复数+1
        apComment.setReply(apComment.getReply()+1);
        mongoTemplate.save(apComment);
    }

    @Override
    public ResponseResult saveCommentRepayLike(CommentRepayLikeDTO dto) {
//        1. 参数校验
//        评论id不能为空  operation必须为 0  或  1
        if (dto.getOperation().intValue() != 0 && dto.getOperation().intValue() != 1){
            log.error("like operation必须为 0  或  1,其值为{}",dto.getOperation());
            CustException.cust(AppHttpCodeEnum.PARAM_INVALID);
        }
//        2. 根据评论id查询评论数据， 为空返回错误信息
        ApUser user = AppThreadLocalUtils.getUser();
        if (user == null){
            CustException.cust(AppHttpCodeEnum.NEED_LOGIN);
        }
        String commentRepayId = dto.getCommentRepayId();
        Query query = Query.query(Criteria.where("id").is(commentRepayId));
        ApCommentRepay apCommentRepay= mongoTemplate.findOne(query, ApCommentRepay.class);
        if (apCommentRepay == null){
            log.error("saveCommentRepayLike 点赞的评论数据不存在，commentId为{}",commentRepayId);
            CustException.cust(AppHttpCodeEnum.PARAM_INVALID);
        }
//        3. 如果是点赞操作 判断是否已经点赞
        ApCommentRepayLike apCommentRepayLike = mongoTemplate.findOne(Query.query(Criteria.where("commentRepayId").is(commentRepayId).and("authorId").is(user.getId())), ApCommentRepayLike.class);
        if (dto.getOperation().intValue() == 0){
//              点过赞提示 请勿重复点赞
            if (apCommentRepayLike != null){
                log.error("like 不能重复点赞，commentId为{}，点赞ID为{}",commentRepayId,apCommentRepayLike.getId());
                CustException.cust(AppHttpCodeEnum.DATA_NOT_ALLOW,"不能重复点赞");
            }
//              未点过赞   保存点赞信息到mongo
            apCommentRepayLike = new ApCommentRepayLike();
            apCommentRepayLike.setCommentRepayId(commentRepayId);
            apCommentRepayLike.setAuthorId(user.getId());
            mongoTemplate.save(apCommentRepayLike);
//              并修改评论信息的点赞数量( + 1)
            apCommentRepay.setLikes(apCommentRepay.getLikes()+1);
            mongoTemplate.save(apCommentRepay);

        }else {
//        4. 如果是取消点赞操作  删除点赞信息
            if (apCommentRepayLike == null){
                log.error("like 尚未点赞，不能取消，commentId为{}",commentRepayId);
                CustException.cust(AppHttpCodeEnum.DATA_NOT_ALLOW,"尚未点赞");
            }
            mongoTemplate.remove(apCommentRepayLike);
//        并修改评论信息的点赞数量( - 1) , 要判断下别减成负数
            apCommentRepay.setLikes(apCommentRepay.getLikes()>0 ? apCommentRepay.getLikes()-1 : 0);
            mongoTemplate.save(apCommentRepay);
//        5. 返回结果时，需要返回点赞点赞数量  返回的key要求必须是:  likes
        }
        Map map = new HashMap();
        map.put("likes",apCommentRepay.getLikes());
        return ResponseResult.okResult(map);
    }
}
